package cn.practice.chat.security;

import cn.hutool.json.JSONUtil;
import cn.practice.chat.lang.Result;
import lombok.extern.slf4j.Slf4j;
import org.springframework.security.access.AccessDeniedException;
import org.springframework.security.web.access.AccessDeniedHandler;
import org.springframework.stereotype.Component;

import javax.servlet.ServletException;
import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

/**
 * @ClassName 拒绝访问处理器
 * @Description:
 * @Author A-TAO
 * @Date 2022/10/19
 * @Version V1.0
 **/
@Slf4j
@Component
public class AccessRefuseHandler implements AccessDeniedHandler {

    @Override
    public void handle(HttpServletRequest request, HttpServletResponse response, AccessDeniedException accessDeniedException) throws IOException, ServletException {
        log.info("开始进入JwtAccessDeniedHandler");
        response.setContentType("application/json;charset=UTF-8");
        String msg = accessDeniedException.getMessage();
        int status = HttpServletResponse.SC_FORBIDDEN;
        response.setStatus(status);
        ServletOutputStream outputStream = response.getOutputStream();
        Result result = Result.error(status, msg );

        outputStream.write(JSONUtil.toJsonStr(result).getBytes("UTF-8"));

        outputStream.flush();
        outputStream.close();

    }
}
